#!/usr/bin/env python
# encoding: utf-8

def get_lora_cmd(lora_addr='', cid='', cmd='',info=''):
    header = 'AA'
    data = cid+cmd+info
    print(data)
    length = hex(int(len(data)/2)).replace('0x','').zfill(2)[-2:]
    if len(data)>0 and len(data) % 2 == 0:
        data_list = [int(data[i:i+2], 16) for i in range(0,len(data)) if i%2==0]
        _sum = hex(sum(data_list) % 256).replace('0x','').zfill(2)[-2:]
        # 重组命令
        print(data)
        new_cmd = lora_addr+header+length+data+_sum
        print(new_cmd)
        cmd_list = [int(new_cmd[i:i+2],16) for i in range(0,len(new_cmd)) if i%2==0]
        print(cmd_list)
        cmd_bytes = bytes(cmd_list)
        print(cmd_bytes)
        return cmd_bytes


recv = 'AA054E010001A6F6'
def cmd_deal(recv):
    '''串口处理命令，监测校验和是否正确'''
    if recv.startswith('AA'):
        data = recv[4:-2]
        theory_len =  int(recv[2:4], 16)
        real_len = int(len(data)/2)
        if theory_len == real_len:
            data_list = [int(data[i:i+2], 16) for i in range(0,len(data)) if i%2==0]
            real_sum = sum(data_list) % 256
            theory_sum = int(recv[-2:], 16)
            if real_sum == theory_sum:
                addr    = data[0:8]
                cmd     = data[8:10]
                content = data[10:]
                print("接收到正确命令: %s"%recv)
                return addr, cmd, content


addr, cmd, content = cmd_deal(recv)
print( addr, cmd, content )
get_lora_cmd('ff0112', "4e010001", "a3",'')
